# ...existing code...
from pathlib import Path
import sqlite3

root = Path(__file__).resolve().parents[1]
db_path = root / 'db' / 'autobuild.db'
out_path = root / 'db' / '-- SQLite.sql'

print('Exporting schema from', db_path, 'to', out_path)
con = sqlite3.connect(db_path)
cur = con.cursor()
# Get schema objects in a sensible order
cur.execute("SELECT type, name, sql FROM sqlite_master WHERE sql NOT NULL AND type IN ('table','index','view','trigger') ORDER BY CASE type WHEN 'table' THEN 1 WHEN 'view' THEN 2 WHEN 'index' THEN 3 WHEN 'trigger' THEN 4 ELSE 5 END, name;")
rows = cur.fetchall()
with open(out_path, 'w', encoding='utf-8') as f:
    f.write('-- SQLite schema export\n')
    for r in rows:
        t, name, sql = r
        f.write(f"-- {t} {name}\n")
        f.write(sql.rstrip() + ';\n\n')

con.close()
print('Export complete, wrote', len(rows), 'objects')
